﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;

namespace WindowsFormsApplication1
{
    class TerminalCommunication
    {

        SerialPort dataport;
        string wholeBuffer; // will have all text 
        string currentBuffer; // have text for currect command
        string reply; //reply for command
        public TerminalCommunication(SerialPort inPort)
        {
            dataport = inPort;
            dataport.DataReceived += new SerialDataReceivedEventHandler(dataport_DataReceived);
        }

        void dataport_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort data = (SerialPort)sender;
            currentBuffer += data.ReadExisting();
            wholeBuffer += currentBuffer;
        }
        public void open()
        {
            dataport.Open();
        }

        public void close()
        {
            dataport.Close();
        }

        void generateEscapeSequence()
        {
            generateEscape();
            Thread.Sleep(100);
            generateEscape(); 
            Thread.Sleep(100);
            generateEscape(); 
            Thread.Sleep(100);
            generateEscape();
        }

        void generateEscape()
        {
            byte[] buffer = new byte[1];
            buffer[0] = 0x1B;
            dataport.Write(buffer, 0, 1);
        }

        public void sendCommand(string command)
        {
            currentBuffer = "";
            generateEscapeSequence();
            Thread.Sleep(100);
            generateEscape();
            dataport.Write(command);

            Thread.Sleep(100);
            generateEscapeSequence();
        }
        
    
    }
}
